package com.mr.dao.util;

import java.util.Collection;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Restrictions;

import com.mr.dao.entity.BaseEntity;

public class CriteriaUtil {

	private CriteriaUtil() {
	}

	public static Criteria generateCriteria(Session session, Class<? extends BaseEntity> clazz, String[] names,
			Object[] values) {
		Criteria criteria = null;
		if (names != null && values != null && names.length == values.length) {
			criteria = create(session, clazz);
			for (int i = 0; i < names.length; i++) {
				Object value = values[i];
				if (value == null) {
					criteria.add(Restrictions.isNull(names[i]));
					continue;
				}
				Class<?> vClazz = value.getClass();
				if (value instanceof Collection) {
					criteria.add(Restrictions.in(names[i], (Collection<?>) values[i]));
					continue;
				} else if (vClazz.isArray()) {
					criteria.add(Restrictions.in(names[i], (Object[]) values[i]));
					continue;
				}

				criteria.add(Restrictions.eq(names[i], values[i]));
			}
		}
		return criteria;
	}

	public static Criteria addAlias(Criteria criteria, Class<? extends BaseEntity> entity, String name) {
		return criteria.createAlias(entity.getName(), name);
	}

	public static Criteria create(Session session, Class<?> clazz) {
		Criteria criteria = session.createCriteria(clazz);
		return criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
	}

	@SuppressWarnings("unchecked")
	public static <T> List<T> list(Criteria criteria) {
		return criteria.list();
	}

}
